import axios from "axios";
import proxy from "@/configs/host";

const env = import.meta.env.MODE || "development";
// 确保env类型匹配proxy对象的键
const API_HOST = proxy[env as keyof typeof proxy].API;

const TIMEOUT = 5000;

export const instance = axios.create({
  baseURL: API_HOST,
  timeout: TIMEOUT,
  withCredentials: false,
});

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json";
    const token = localStorage.getItem("HIST-token");
    if (token) {
      config.headers["Authorization"] = `${token}`;
    }
    return config;
  },
  (error) => {
    if (error.response.status === 401) {
      localStorage.clear()
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default instance;
